package com.baymax.study.redisson.controller;

import com.baymax.study.atomic.tools.ResultMsg;
import com.baymax.study.redisson.constants.Constant;
import com.baymax.study.redisson.infrastructure.locks.annotation.GlobalLock;
import com.baymax.study.redisson.infrastructure.locks.annotation.GlobalLockParam;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author baymax
 * @since 2025-05-20
 */
@Slf4j
@RestController
@RequestMapping("/redis")
public class RedissonController {
    /**
     * 分布式锁测试
     *
     * @param key 锁的建
     * @return 返回数据结果
     * @throws InterruptedException ex
     */
    @GetMapping("/lock")
    @GlobalLock(name = Constant.LOCK_NAME)
    public ResultMsg redisLock(@GlobalLockParam String key) throws InterruptedException {
        log.info("redisLock key:{}", key);

        TimeUnit.SECONDS.sleep(2);

        return ResultMsg.buildSuccess();
    }

    @PostMapping("/lock")
    @GlobalLock(name = Constant.LOCK_NAME)
    public ResultMsg redisLock(@GlobalLockParam("subDto.key") @RequestBody RequestDto requestDto) throws InterruptedException {
        log.info("redisLock key:{}", requestDto);

        TimeUnit.SECONDS.sleep(2);

        return ResultMsg.buildSuccess();
    }

    @Data
    public static class RequestDto {
        private String key;

        private SubDto subDto;
    }

    @Data
    public static class SubDto {
        private String key;
    }
}
